//
//  CYBottomViewController.m
//  CYTabBarViewController
//
//  Created by lc4y on 2017/12/4.
//  Copyright © 2017年 weiwang. All rights reserved.
//

#import "CYBottomViewController.h"
#import "CYBottomViewControllerCollectionViewCell.h"

@interface CYBottomViewController ()

@end

@implementation CYBottomViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [_cy_collectionView registerClass:[CYBottomViewControllerCollectionViewCell class]  forCellWithReuseIdentifier:CYCollectionCell];
    _cy_collectionView.pagingEnabled = YES;
    
    [self.view addSubview:_cy_collectionView];
    [self cy_configLayoutSubViews];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(self.cy_tabBarController.titleView.cy_width, self.cy_tabBarController.titleView.cy_height);
}

- (void)cy_refreshCollectionCell:(UICollectionViewCell *)collectionCell indexPath:(NSIndexPath *)indexPath {
    CYBottomViewControllerCollectionViewCell *bottomVCCell = (CYBottomViewControllerCollectionViewCell *)collectionCell;
    
    if( bottomVCCell.currentVC && bottomVCCell.currentV ) {
        [bottomVCCell.currentV removeFromSuperview];
        [bottomVCCell.currentVC removeFromParentViewController];
    }
    
    UIViewController *viewController = _cy_dataArray[indexPath.row];
    [bottomVCCell.contentView addSubview:viewController.view];
    [self addChildViewController:viewController];
    [viewController didMoveToParentViewController:self];
    bottomVCCell.currentVC = viewController;
    bottomVCCell.currentV = viewController.view;
}

- (void)setCy_currentIndex:(NSInteger)cy_currentIndex {
    if( cy_currentIndex >= _cy_dataArray.count ) {
        return;
    }
    
    _cy_currentIndex = cy_currentIndex;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0000001 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        _cy_collectionView.contentOffset = CGPointMake([UIScreen mainScreen].bounds.size.width * cy_currentIndex, 0);
    });
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger scrollIndex = scrollView.contentOffset.x / [UIScreen mainScreen].bounds.size.width;
    if (self.delegate && [self.delegate respondsToSelector:@selector(bottomViewMenuClick:)]) {
        [self.delegate bottomViewMenuClick:scrollIndex];
    }
}

@end
